package filter;

import bo.IpObject;
import io.netty.handler.ipfilter.IpFilterRule;
import io.netty.handler.ipfilter.IpFilterRuleType;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liutao
 * Date 2021/7/15 12:32 下午
 * Description: 实现ip过滤器
 * Version: 1.0
 **/
public  class IpFilterRuleHandler implements IpFilterRule {


    private   long ipToLong(String ip) {
        String[] ipArray = ip.split("\\.");
        List<Long> ipNums = new ArrayList<Long>();
        for (int i = 0; i < 4; ++i) {
            ipNums.add(Long.parseLong(ipArray[i].trim()));
        }
        return ipNums.get(0) * 256L * 256L * 256L
                + ipNums.get(1) * 256L * 256L + ipNums.get(2) * 256L
                + ipNums.get(3);
    }

    @Override
    public boolean matches(InetSocketAddress inetSocketAddress) {
        //ip转成long类型
        String ip = inetSocketAddress.getHostString();
        long ipLong = ipToLong(ip);

        //创建一个要过滤的ip段
        IpObject ipRange = new IpObject("172.31.1.81", "172.31.1.87");

        long ipStart = ipToLong(ipRange.getIpStart());
        long ipEnd = ipToLong(ipRange.getIpEnd());
        //比较ip区间
        //返回true则执行过滤器
        return ipLong >= ipStart && ipLong <= ipEnd;
    }

    @Override
    public IpFilterRuleType ruleType() {
        //返回拒绝则表示拒绝连接，反之返回接受则表示可以连接
        return IpFilterRuleType.REJECT;
    }
}
